泛型
TIP
定义的时候,不关心具体的类型
在使用的时候,TypeScript的type system能够更加有效的检查,帮助开发者知道类型
const names: Array<string> = [];
const promise: Promise<string> = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("success:)");
}, 3000);
});
promise.then((data) => {
data.split("");
});
Function泛型
TIP
tsc会自动推断,可以让我们不用写多余的代码,如方法的返回值,调用方法时传入具体的类型
function merge<T, U>(objA: T, objB: U) {
// return 的类型会推断为 T & U
return Object.assign(objA, objB);
}
// merge<{name: string;hobbies: string[];}, {score: number;}>(参数。..)
const mergedObj = merge(
{ name: "Aeroxian", hobbies: ["Codeing", "Reading"] },
{ score: 100 }
);
console.log(mergedObj);
Constraints约束
TIP
improve function
function merge<T, U extends object>(objA: T, objB: U) {
return Object.assign(objA, objB);
}
// error will not work
//const mergedObj = merge({ name: "Aeroxian", hobbies: ["Codeing", "Reading"] }, "");
extends interface⭐
TIP
约束接口,方法的内容操作聚焦接口规范
interface Lengthy {
length: number;
}
function countAndDescribe<T extends Lengthy>(element: T) {
let descriptionText = "Got no value.";
if (element.length === 1) {
descriptionText = "Got 1 element.";
} else if (element.length > 1) {
descriptionText = `Got ${element.length} elements.`;
}
return [element, descriptionText];
}
console.log(countAndDescribe(["Coding","Reading"]));
keyof⭐
TIP
在泛型中加强泛型之间的约束
function extractAndConvert<T extends object, U extends keyof T>(
obj: T,
key: U
) {
return "Value: " + obj[key];
}
// error
// extractAndConvert({ name: "Aeroxian" }, "age");
console.log(extractAndConvert({ name: "Aeroxian" }, "name"));
Generic class
class DataStorage<T extends string | number | boolean> {
private data:T[] = [];
addItem(item: T) {
this.data.push(item);
}
removeItem(item:T){
const index = this.data.indexOf(item);
if(index === -1){
return ;
}
this.data.splice(index,1);
}
getItems(){
return [...this.data]
}
}
const textStorage = new DataStorage<string>();
Generic utils type
TIP
TypeScript中集成了许多内置的泛型类用于开发使用
ReadOnly
const cities: Readonly<string[]> = ["BeiJing", "GuiLin"];
// error
//cities.pop();
partial
function createCourseGoal(
name: string,
description: string,
completeUtil: Date
) {
// Partial的作用Make all properties in T optional
//let courseGoal: CourseGoal = {};
let courseGoal: Partial<CourseGoal> = {};
courseGoal.name = name;
courseGoal.description = description;
courseGoal.completeUtil = completeUtil;
return courseGoal as CourseGoal;
}
